package com.zdy.socketserver.client;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author myh
 * @date 2024/6/12
 * 解码器,解决拆包粘包问题
 */
@Slf4j
public class NettyMsgDecoder extends ByteToMessageDecoder {
    int length = 0;
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if(byteBuf.readableBytes()>4){
            if(length==0){
                length = byteBuf.readInt();
            }
            if(byteBuf.readableBytes()<length){
                log.info("长度不够，继续等待");
            }else{
                byte[] bytes = new byte[length];
                byteBuf.readBytes(bytes);
                NettyMsg message = new NettyMsg();
                message.setLength(length);
                message.setContent(bytes);
                //发送给下一个handler
                list.add(message);
                length = 0;
            }
        }
    }
}
